<div class="full-screen">
    <header class="bg-none" style="position: fixed;top: 0;width: 100%;box-sizing: border-box">
        <a href="javascript:history.back()" class=" u-left" ><i class="arr left"></i></a>
        <!--<p class="u-title">商品详情</p>-->
        <a id="scanQR" class="u-right scanQR"><img src="/wap_themes/xiaomi/images/icon/QR-icon1.png" alt=""></a>
    </header>

    <form action="<{link app=b2c ctl=wap_cart act=add arg0=goods}>" method="post" id="buy_form" data-type="ajax">
        <input type="hidden" name="btype" class="btype"><!-- value="is_fastbuy" 立即购买提交的时候要带上这个值 -->
        <input type="hidden" name="goods[goods_id]" value="<{$page_product_basic.goods_id}>"/>
        <input type="hidden" name="prepare_type" value="<{$page_product_basic.promotion_type}>">
        <input type="hidden" name="goods[product_id]" value="<{$page_product_basic.product_id}>"/ >
        <input type="hidden" name="min" value="1" class="min-num" />
        <input type="hidden" name="max" value="<{$product_store.store}>" class="max-num" />
<!--         <input type="hidden" name="max" value="<{if $gift!="havegift"}><{$product_store.store}><{else}><{$maxbuy}><{/if}>" class="max-num" /> -->
        <input type="hidden" name="mini_cart" value="true"/>
        <!-- 商品图片 -->
        <div class="page pt-pic">
            <{include file='wap/product/info/pic.html'}>
        </div>
        <!-- 商品标题 -->
        <h1 class="pt-name">
            <{$page_product_basic.title}>
            <{ if $page_product_basic.promotion_type == 'prepare'}>
            <span style="color:#fff;background:red;font-weight:bold;">预售</span>
            <{/if}>
        </h1>
        <!-- 商品价格 -->
        <div class="col2 pt-price">
        <{ if $page_product_basic.promotion_type != 'prepare'}>
            <{if $page_product_basic.goods_marketable == 'true'}>
                <{include file='wap/product/info/price.html'}>
            <{/if}>
        <{/if}>
        <{ if $page_product_basic.promotion_type == 'prepare'}>
            <{if $page_product_basic.goods_marketable == 'true'}>
                <{include file='wap/product/prepare/price.html'}>
            <{/if}>
        <{/if}>
        </div>
        <{ if $page_product_basic.promotion_type != 'prepare'}>
        <!-- 促销信息 -->
            <{include file='wap/product/info/promotion.html'}>
        <{/if}>
        <!-- 商品规格 -->
        <{if $show_status!='off'}>
        <div class="pt-sku">
            <{include file='wap/product/info/spec.html'}>
        </div>

        <!-- 商品数量 -->
        <!-- edit by hzk to add peraddnum  批量设置-->
        <{ if $page_product_basic.promotion_type != 'prepare'}>
        <div class="pt-num J-pt-num" style="padding: .2rem .2rem .2rem 2.5rem ;">
            <{if $product_store.store <= 5}>
            <!--<span class="warn-message">余量有限</span>-->
            <{/if}>

            <label for="goods_num">数量：</label>
            <span class="minus btn">-</span>
            <div class="num">
                <!-- <input type="number" name="goods[num]" id="goods_num" value="<{if $data.add.isused==1}><{$data.add.pernum}><{else}><{$data.add.peradd}><{/if}>" class="num-ipt"> -->
                <input type="number" name="goods[num]" id="goods_num" value="<{if $data.add.isused==1}><{$adta.add.quantity}><{else}><{$data.add.quantity}><{/if}>" class="num-ipt">
                <input type="hidden"  class="action-quantity-input-havegift"  value="<{$gift}>">
                <input type="hidden"  class="action-quantity-input-havegift"  value="<{$gift}>">
                <input type="hidden"  class="action-quantity-input-getmaxbuy"  value="<{if $gift =="havegift"}><{$maxbuy|number}><{else}>0<{/if}>">
            </div>
            <span class="plus btn">+</span>
            <a href="#" class="u-cart-btn" id="J_buy_btn">
                <p>加入购物车</p>
            </a>
        </div>
        <{/if}>
        <!-- 预售商品 -->
        <{ if $page_product_basic.promotion_type == 'prepare'}>
        <input type="hidden" name="goods[num]" id="goods_num" value="1" class="num-ipt">
        <{/if}>
        <!--购买按钮-->
        <div class="pt-btn" style="list-style-type:none">
            <a class="btn orange scanQR">
                <!--<img src="/wap_themes/xiaomi/images/icon/QR-icon1.png" alt="">-->
                扫一扫
            </a>
        <{ if $page_product_basic.promotion_type != 'prepare'}>
            <{include file='wap/product/info/btn.html'}>
        <{/if}>
        <!--<{ if $page_product_basic.promotion_type == 'prepare'}>-->
            <!--<{include file='wap/product/prepare/btn.html'}>-->
        <!--<{/if}>-->
        </div>
    <{/if}>
    </form>
    <img src="<{link app=b2c ctl=wap_product act=cron arg=$page_product_basic.goods_id }>" width="1" border="none" height="1">
    <div class="pt-detail">
        <div class="tab J-tab">
            <ul class="trigger-list">
                <li class="trigger act">
                  商品详情
                </li>
                <li class="trigger" data-url="<{link app=b2c ctl=wap_product act=productBasicIntro arg0=$page_product_basic.product_id}>">
          基本信息
                </li>
            <{if $setting.acomment.switch.discuss == 'on'}>
                <li class="trigger" data-url="<{link app=b2c ctl=wap_product act=goodsDiscussInit arg0=$page_product_basic.goods_id arg1=$page_product_basic.product_id}>" >
                  用户评论<{$discussCount|default:'0'}>
                </li>
            <{/if}>
            <{if $setting.acomment.switch.ask == 'on'}>
                <li class="trigger" data-url="<{link app=b2c ctl=wap_product act=goodsConsultInit arg0=$page_product_basic.goods_id arg1=$page_product_basic.product_id}>" >
                  用户咨询<{$askCount|default:'0'}>
                </li>
            <{/if}>
            </ul>
            <ul class="panel-list">
                <li class="panel act">
                <{include file='wap/product/tab/detail_intro.html'}> <!-- 商品详情 -->
                </li>
                <li class="panel"> </li>
                <li class="panel"> </li>
                <li class="panel"> </li>
            </ul>
        </div>
    </div>
</div>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>
(function(){
    /*图片滚动*/
    var ptSlider = $('#J_pt_slider');
    var inner=ptSlider.find('.slider-list');
    var item = inner.find('.slider-item');
    var sl = item.size();
    var sw = item.width() + parseInt(item.css('margin-left')) + parseInt(item.css('margin-right'));
    var speed = 200;
    var act = 0;
    var x1,x2, direct;
    
    function transformBox(obj,value,time){
        var time=time?time:0;
        transl="translate3d("+value+"px,0,0)";
        obj.css({'-webkit-transform':transl,'-webkit-transition':time+'ms linear'});
    }
    inner.css({'width':sl * sw, '-webkit-transform': 'translate3d(50px,0,0)'});
    ptSlider.on('touchstart', function(e) {
        if(x2) x2 = undefined;
        x1 = e.touches[0].pageX;
    })
    .on('touchmove', function(e){
        e.preventDefault();
        x2 = e.touches[0].pageX;
        var offset= x2-x1+act*sw;
        transformBox(inner,offset + 50,0);
    })
    .on('touchend', function(e) {
        if(x1 > x2) direct = 'left';
        else direct = 'right';
        if(Math.abs(x1 - x2) < 30) 
        transformBox(inner,act * sw + 50,100);
    })
    .swipe(function(e){
        var offset;
        if(direct == 'left') {
            --act;
        }
        else {
            ++act;
        }
        if(act == 1){
            act = 0;
        }
        else if(act == -sl){
            act = - sl + 1;
        }
        offset=act*sw;
        transformBox(inner, offset + 50,speed);
        $(this).next().children().eq(Math.abs(act)).addClass('act').siblings('.act').removeClass('act');
    });
    /*图片滚动End*/
    
    /*规格*/
    var selected = $('#J_all_sku .selected .v');
        $('#J_sel_sku').on('touchend',function(e){e.preventDefault();}).on('tap',function(e){
        $(this).addClass('hide').next('.sel-sku-box').removeClass('hide');
    });
    $('#J_all_sku .close').on('tap',function(e){
        setTimeout(function(){
            $('#J_all_sku').addClass('hide');
            $('#J_sel_sku').removeClass('hide');
        },500)
    });
    /*规格End*/

    /*SetCookie*/
    function setCookie(name,value,hours){  
        var d = new Date();
        d.setTime(d.getTime() + hours * 3600 * 1000);
        document.cookie = name + '=' + value + '; expires=' + d.toGMTString();
    }
    function getCookie(name){  
        var arr = document.cookie.split('; ');
        for(var i = 0; i < arr.length; i++){
            var temp = arr[i].split('=');
            if(temp[0] == name){
                return temp[1];
            }
        }
        return '';
    }
    function removeCookie(name){
        var d = new Date();
        d.setTime(d.getTime() - 10000);
        document.cookie = name + '=1; expires=' + d.toGMTString();
    };
    var referrer = document.referrer;
    var action = window.location.href;
    var reRex;
        reRex = referrer.replace(/-\d+\.html$/,''),
        action = action.replace(/-\d+\.html$/,'');
    if(reRex !=action){
        setCookie("referrer", referrer,0.5);
    }
    console.log(getCookie("referrer"))
    $(".a-back").attr('href', getCookie("referrer"));
    /*SetCookie End*/

    $('#J_all_price').on('tap',function(e){
        new Dialog('.all-price');
    });

    
    
    //add by hzk 2017-5-24  增加提示时间
    function popuphzk(msg) {
	  alert(msg );
    }
    //add end
  //== 赠品封顶值提示方法 add by hzk 2017-5-18
//== 赠品封顶值提示方法 add by hzk 2017-5-18
    	function checkmaxbuy(e1, value,inputtype) {
    		
    		 //add by hzk 2017-5-18
    	  var checkgift = e1.find('.action-quantity-input-havegift').val();	           
    	  if('havegift'==checkgift){
    		   var getmaxbuy = e1.find('.action-quantity-input-getmaxbuy').val();
    	      	
    	 		// alert(00000);   
    					if(inputtype=='button' && getmaxbuy == value){
    	 		 //alert(2222222);   
    	 		popuphzk('该商品购买数量已达赠品优惠上限'+getmaxbuy+'，上限之后的购买数量将不赠送赠品，确定继续购买？');
    		            }else if(inputtype=='text' && getmaxbuy<=value){
    	 		 //alert(3333333);   
    	 		popuphzk('该商品仅在前'+getmaxbuy+'个商品赠送赠品，上限数量之后的购买数量将不赠送赠品，确定继续购买？');
    		            }
    	 	 //alert(getmaxbuy);   
    	  }
    	}

    /* <{if $data.add.isused==1}><{$data.add.pernum}><{else}><{$data.add.peradd}><{/if}> */
// 设置商品数量
function setQuantity(el,flag){
    	
    //nostore_sell	
	    	
    var ipt = el.parent().find('.num-ipt'),
        max = parseInt(el.parents('form').find('.max-num').val()),
        min = parseInt(el.parents('form').find('.min-num').val()),
        val = parseInt(ipt.val());
    
    var peradd =  parseInt((<{$data.add.isused}> ==1) ?  <{$data.add.pernum}>  : <{$data.add.peradd}>) ; 
    var res =parseInt(0);
    min=peradd;
    
    
  //add by hzk 2017-5-25
    
    //add by hzk 2017-5-25
      var nostore_sell = <{$page_product_basic.nostore_sell}>;
      if(nostore_sell==1){
      	max = 999999;
       }
  
  
	if(flag==2){
		checknum=val+peradd;
		//alert(el.parent());
		checkmaxbuy(el.parent(), checknum,'button'); 
	}
	
	if(flag==3){
		//alert(el.parent());
		checkmaxbuy(el.parent(), val,'text'); 
	}
	
	//add end 
    
    switch(flag){
        case 1:
            if(!/^\d+$/.test(val)) 
                ipt.val(min);
            else if(val > min){
            	//hzk
            	if(!(0 ==(val%peradd))){
            		res = val - (val%peradd);
            	}else{
            		res = val - peradd;
            	}
                    ipt.val( res );

            }
            else if(val <= min)
            {
                //@mo edit
                if(max==0){
                    popup('缺货已无法再订购');
                    ipt.val( 0 );
                    break;
                }
                ipt.val( min );
                popup('此商品最少购买' + min + '件');
            }
            break;
        case 2:
            if(val < max){
            	
            	//hzk
                if(!(0 ==(val%peradd))){
               		 res = (val- parseInt(val%peradd)) +  parseInt(peradd);
               	 }else{
               		 res = parseInt(val) + parseInt(peradd);
               	}
                if(res >= max)
                    ipt.val( max );
                else
                    ipt.val( +parseInt(res) );

            }
            else if(val >= max)
            {
                //@mo edit
                ipt.val( max );
                if(max==0){
                    popup('缺货已无法再订购');
                    break;
                }
                popup('此商品最多只能购买' + max + '件');
            }
            break;
        case 3:
            if(!/^\d+$/.test(val)) {
                ipt.val(min);
            } else if(val > max){
                popup('此商品最多只能购买' + max + '件');//光标设置
                ipt.val(max);
            } else if(val < min){
                popup('此商品最少购买' + min + '件');
                ipt.val(min);
            }
            break;
    }


        // add by lkb 2017.05.17 设置发货提醒
        var productid='<{$page_product_basic.product_id}>';
        var val=parseInt(ipt.val());
            $.post('<{link app=b2c ctl=wap_product act=ajax_product_getdelivery}>','productid='+productid+'&val='+val+'',function(re){
                $('.goods_tips').html(re);
            });
        //add end


}
function popup(msg) {
    var tpl = $('<div class="popup">' + msg + '</div>').appendTo(document.body);
    var timer = setTimeout(function(){
        tpl.remove();
    }, 3000);
}

$('.J-pt-num').on('tap',function(e){
    var el = $(e.srcElement),
        n = 0;
    if( !el.hasClass('btn') )return;

    if( el.hasClass('minus') )n=1;
    if( el.hasClass('plus') )n=2;

    setQuantity(el,n);

});
$('.num-ipt').on('change',function(){
    setQuantity( $(this),3 );
});

  $('#J_buy_btn').on('click',function(e){
      var e = $.fn.cookie('UNAME')?$.fn.cookie('UNAME'):'';
      console.log(e);
      if(!e){
          location.href="passport.html";
          return;
      }

      var _min=parseInt("<{$data.add.min_buy}>");
      var _num=parseInt($("#goods_num").val());
      if(_num==0 || _num<_min){
            alert("最低购买数量为"+_min+"件");
            return false;

        }
    //防止先点击 立即购买 返回后点击 加入购物车 出现undefined的错误
	var buy_form_btype = $('#buy_form').find('.btype').val();
	if(buy_form_btype == "is_fastbuy"){
		$('#buy_form').find('.btype').val("");
	}
	  
    var data = $('#buy_form').serialize();
	console.log(data);
    $.post($('#buy_form').attr('action'),data,function(re){
    	//这里  re 是   表单到控制器对应的  add方法   中  echo 的值 
      if(re == 1)
         {
           popup("购买数量超过限制",2000);
         }
         else
         {
			if(re){
	            try{
	                result = $.parseJSON(re);
	                //alert(result);
	            	popup(result.error,800,"sm-pop");
	                }
                catch (e){
                    popup("已加入购物车",2000);//修改购物车为订货单 by wpn
                }
            }
		}
	
		    });
    return false;
  });
    $("#goods_num").on("blur",function(){

        var min_num=parseInt("<{$data.add.min_buy}>");
        var num=$("#goods_num").val();
        if(num%min_num!=0){
            alert("购买数量必须以"+min_num+"为单位");

        }

    });
  $('#J_fast_buy').on('click',function(e){

      var min=parseInt("<{$data.add.min_buy}>");
      var num=$("#goods_num").val();
      if(num%min!=0){
          alert("购买数量必须以"+min_num+"为单位");
            return false;
      }
      if($("#goods_num").val()<min){
          alert("最小购买"+min+"件");
          e.stopPropagation();
          return false;

      }
//
//
//
    $('#buy_form').find('.btype').val('is_fastbuy');
//    $('#buy_form').submit();
    return false;
  });
  $('.pt-promotions').on('touchend',function(e){e.preventDefault();}).on('tap',function(){
    new Dialog('.promotions-panel',{title:'促销活动'});
  });
  $('.promotions-panel .trigger').on('tap',function(){
    if( $(this).hasClass('act') ) return;
    var n = $(this).addClass('act').siblings().removeClass('act').attr('data-target'),
    par = $(this).parent().siblings().removeClass('act');
    !!n ? (par.eq(n-1).addClass('act')) : (par.eq(n+1).addClass('act'));
  });

    // 初始化购物车的收藏按钮状态
    $.post('<{link app=b2c ctl=wap_product act=is_fav}>','goods_id=<{$page_product_basic.goods_id}>',function(re){
      if(re==1){
        $('.favlist').removeClass('btn-addfav').addClass('btn-faved').html('已收藏');
      }
    });

    //收藏商品
    $('.btn-addfav').bind('click',function(){
        var $this = $(this);
        if($this.hasClass('btn-faved')) return;
        var data = 'gid='+$this.attr('data-gid')+'&type=goods';
        $.post('<{link app=b2c ctl=wap_member act=ajax_fav}>',data,function(re){
            //var re = $.parseJSON(re);
            //if(re.success){
                //$this.hide().next().show();
                $this.removeClass('btn-addfav').addClass('btn-faved').html('已收藏');
            //}
        });
        return false;
    });

})();

    $(function () {



        //生成签名

        var appid="<{$SignPackage.appId}>";
        var timestamp="<{$SignPackage.timestamp}>";
        var nonceStr="<{$SignPackage.nonceStr}>";
        var signature="<{$SignPackage.signature}>";
        wx.config({
            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            debug: false,
            // 必填，公众号的唯一标识result.appId
            appId: appid,
            // 必填，生成签名的时间戳result.timestamp
            timestamp: timestamp,
            // 必填，生成签名的随机串
            nonceStr: nonceStr,
            // 必填，签名，见附录1
            signature: signature,
            // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            jsApiList : [ 'checkJsApi', 'scanQRCode' ]
        });
        wx.error(function(re) {
//            alert("出错了：" + re.errMsg);
        });
        wx.ready(function() {
            wx.checkJsApi({
                jsApiList : ['scanQRCode'],
                success : function(res) {

                }
            });
            //点击扫码按钮
            $(".scanQR").click(function(){

                wx.scanQRCode({
                    needResult : 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                    scanType : [ "qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                    success : function(res) {

                        var res = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                        var pattern=/,/;
                        if(pattern.test(res)){
                            var s=res.split(",");
                            res=s[1];
                        }
                        $.post("<{link app=b2c ctl=wap_gallery act=getqrcode_data arg0='"+res+"'}>",function (re) {
                            $.ajax({
                                type: "GET",
                                cache: false,
                                url: re,
                                data: "",
                                success: function() {
                                    location.href=re;
                                },
                                error: function() {
                                    alert("此条码无效");
                                }
                            });
                        })
                    },
                    error: function() {
                        alert("此条码无效");
                    }
                });
            });
        });
    });

$(function () {
    $("#J_fast_buy").on("click",function (e) {
        $form=$(this).parents("form");
        var url=$form.attr("action");
        if($form.attr("data-type")=='ajax'){

            console.log($form.serialize())
            $.post(url,$form.serialize(),function (re) {
                re=JSON.parse(re);
                console.log(re);
                if(re.success){

                    location.href=re.redirect;
                }
                else{
                    alert(re.error);
                }
            })
        }
    })
});

</script>
